//
//  MainPageViewController.m
//  PHONGDEP
//
//  Created by kidbaw on 8/1/13.
//  Copyright (c) 2013 kidbaw. All rights reserved.
//

#import "MainPageViewController.h"
#import "Define.h"
#import "AppViewController.h"
#import "SBJSON.h"
#import "UIImageView+WebCache.h"
#import "RoomDetailView.h"
#import "HouseDetailView.h"

#define _TAG_CELL_IMAGE                         1000
#define _TAG_CELL_LTITLE                        1001
#define _TAG_CELL_RTITLE                        1002
#define _TAG_CELL_CONTENT                       1003
#define _TAG_CELL_SUB                           1004
#define _TAG_CELL_SPINNER                       1005
#define _TAG_CELL_AVAILABILITY_IMAGE_VIEW       1006
#define _TAG_CELL_REMAINING_DAY_BUTTON          1007

#define _TAG_BUTTON_MENU                        1010
#define _TAG_BUTTON_LOCATION                    1011

@interface MainPageViewController ()

@end

@implementation MainPageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _APIRequester = [APIRequester new];
    }
    return self;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    _isInitiationAtTheFirstTime = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (_isInitiationAtTheFirstTime) {
        [self initInterface];
        [self setDataForTableView];
        [self loadInterface];
        
        [self loadLeftTableViewAtFistTime];
        
        _isInitiationAtTheFirstTime = NO;
    }
}

- (void)initInterface {
    // PAPER FOLD VIEW
    _paperFoldView = [[PaperFoldView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height)];
    [_paperFoldView setAutoresizingMask:UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth];
    _paperFoldView.delegate = self;
    [self.view addSubview:_paperFoldView];
    
    // MAP VIEW
    _rightMapView = [[MKMapView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width - WIDTH_TABLE_CELL,self.view.frame.size.height)];
    [_rightMapView setUserTrackingMode:MKUserTrackingModeFollowWithHeading];
    _rightMapView.delegate = self;
    
    _rightDirections_MapView = [[SBMapView alloc] initWithFrame:CGRectMake(0, 0, _rightMapView.frame.size.width, _rightMapView.frame.size.height)];
    _rightDirections_MapView.hidden = YES;
    [_rightMapView addSubview:_rightDirections_MapView];
    
        // CURRENT LOCATION
    _btnMap_CurrentLocation = [[UIButton alloc] initWithFrame:CGRectMake(_rightMapView.frame.size.width - 50,0,50,50)];
//    btnMap_CurrentLocation.backgroundColor = [UIColor blueColor];
    [_btnMap_CurrentLocation setBackgroundImage:IMG_ICO_MAP_CURRENT_LOCATION forState:UIControlStateNormal];
    [_btnMap_CurrentLocation addTarget:self action:@selector(gotoCurrentLocation) forControlEvents:UIControlEventTouchUpInside];
    [_rightMapView addSubview:_btnMap_CurrentLocation];
    
        // GET DIRECTIONS
    _btnMap_GetDirections = [[UIButton alloc] initWithFrame:CGRectMake(_rightMapView.frame.size.width - 50,50,50,50)];
//    btnMap_GetDirections.backgroundColor = [UIColor redColor];
    [_btnMap_GetDirections setBackgroundImage:IMG_ICO_MAP_GET_DIRECTIONS forState:UIControlStateNormal];
    [_btnMap_GetDirections addTarget:self action:@selector(getDirectionsFromCurrentLocation) forControlEvents:UIControlEventTouchUpInside];
    _btnMap_GetDirections.hidden = YES;
    [_rightMapView addSubview:_btnMap_GetDirections];
    
    [_paperFoldView setRightFoldContentView:_rightMapView foldCount:3 pullFactor:0.9];
    
    // CENTER VIEW
    float heightToolbar = 44;
    if ([SupportFunction deviceIsIPad]) {
        heightToolbar = 90;
    }
    
    _centerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height)];
    _centerView.layer.shadowColor = [UIColor blackColor].CGColor;
    _centerView.layer.shadowOpacity = 0.6f;
    [_paperFoldView setCenterContentView:_centerView];
    
    _centerTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,heightToolbar,_centerView.frame.size.width,_centerView.frame.size.height - heightToolbar)];
    [_centerTableView setRowHeight:HEIGHT_TABLE_CELL];
    [_centerTableView setDelegate:self];
    [_centerTableView setDataSource:self];
    _centerTableView.backgroundColor = [UIColor colorWithWhite:244/255.f alpha:1.0];
    [_centerView addSubview:_centerTableView];
    
    // TOOLBAR
    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, _centerView.frame.size.width, heightToolbar)];
    [toolBar setBackgroundImage:IMG_BG_MENU_BAR forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
    toolBar.layer.shadowColor = [UIColor blackColor].CGColor;
    toolBar.layer.shadowOffset = CGSizeMake(0, 0);
    toolBar.layer.shadowRadius = 2;
    toolBar.layer.shadowOpacity = 0.6f;
    
    [_centerView addSubview:toolBar];
    
    UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithImage:IMG_ICO_MENU style:UIBarButtonItemStylePlain target:self action:@selector(touchUpInsideButton:)];
    menuButton.tag = _TAG_BUTTON_MENU;
    
    UIBarButtonItem *locationButton = [[UIBarButtonItem alloc] initWithImage:IMG_ICO_LOCATION style:UIBarButtonItemStylePlain target:self action:@selector(touchUpInsideButton:)];
    locationButton.tag = _TAG_BUTTON_LOCATION;
    
    UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    toolBar.items = [NSArray arrayWithObjects:menuButton,flex,locationButton, nil];
    
    _leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0,150,self.view.frame.size.height)];
    [_leftTableView setBackgroundColor:[UIColor colorWithRed:53/255.f green:55/255.f blue:63/255.f alpha:1.0]];
    [_leftTableView setRowHeight:45];
    _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_leftTableView setDataSource:self];
    [_leftTableView setDelegate:self];
    [_paperFoldView setLeftFoldContentView:_leftTableView foldCount:2 pullFactor:0.9];
}

- (void)loadLeftTableViewAtFistTime {
    [_leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:enumMenuTypeRoom inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
    [self tableView:_leftTableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:enumMenuTypeRoom inSection:0]];
}

- (void)loadInterface {
    if (_leftTableView.indexPathForSelectedRow.row == enumMenuTypeHouse) {
        _arrayMain = [PersonDataManager housesShared].categoryArray;
    }
    else {
        _arrayMain = [PersonDataManager roomsShared].categoryArray;
    }
    
    // CENTER TABLE VIEW
    [_centerTableView reloadData];
}

#pragma mark - Actions

-  (void)touchUpInsideButton:(id)sender {
    UIBarButtonItem *button = (UIBarButtonItem*) sender;
    if (button.tag ==_TAG_BUTTON_MENU) {
        if (_paperFoldView.state != PaperFoldStateLeftUnfolded)
            [_paperFoldView setPaperFoldState:PaperFoldStateLeftUnfolded];
        else
            [_paperFoldView setPaperFoldState:PaperFoldStateDefault];
    }
    else if (button.tag ==_TAG_BUTTON_LOCATION) {
        if (_paperFoldView.state != PaperFoldStateRightUnfolded)
            [_paperFoldView setPaperFoldState:PaperFoldStateRightUnfolded];
        else
            [_paperFoldView setPaperFoldState:PaperFoldStateDefault];
    }
    
}

#pragma mark - UITableViewDataSource & UITableViewDelegate

- (void)setDataForTableView {
    _offsetRoom = 0;
    _limitRoom = INT_LIMIT_DEFAULT;
    
    _offsetHouse = 0;
    _limitHouse = INT_LIMIT_DEFAULT;
    
//    _pageSize = 0;
//    if (INTERFACE_IS_PHONE)
//    {
//        _pageSize = 6;
//    }
//    else
//    {
//        _pageSize = 10;
//    }
//    
//    float width = _centerTableView.frame.size.width;
//    float height = _centerTableView.frame.size.height;
//    
//    _marginTop = 0;
//    _marginLeft = 0;
//    _marginCell = 0;
//    
//    _heightCell = (height - _marginTop*2)/_pageSize;
//    _widthCell = width;
    
    _heightCell = HEIGHT_TABLE_CELL;
    _widthCell = WIDTH_TABLE_CELL;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == _leftTableView) {
        return 44;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView == _leftTableView) {
        static NSString* boldFontName = FONT_APP_BOLD;
        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
        header.backgroundColor = [UIColor colorWithRed:53/255.f green:55/255.f blue:63/255.f alpha:1.0];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(7, 7, 30, 30)];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.image = IMG_ICO_LOGO_HEADER;
        [header addSubview:imageView];
        
        UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(43, 12, 100, 20)];
        lblTitle.textColor = [UIColor whiteColor];
        lblTitle.font = [UIFont fontWithName:boldFontName size:12];
        lblTitle.textAlignment = NSTextAlignmentLeft;
        lblTitle.backgroundColor = [UIColor clearColor];
        lblTitle.text = @"PHÒNG ĐẸP.VN";
        lblTitle.adjustsFontSizeToFitWidth = YES;
        [header addSubview:lblTitle];
        
        return header;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _leftTableView)
        return 3;
    else
        return _arrayMain.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifierCellLeft = @"UITableViewCellLeft";
    static NSString *identifierCellCenter = @"UITableViewCellCenter";
    static NSString* fontName = FONT_APP_BOLD;
    static NSString* boldFontName = FONT_APP_BOLD;
    
    UITableViewCell *cell = nil;
    if (tableView == _leftTableView)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:identifierCellLeft];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierCellLeft];
            UIView *myBackView = [[UIView alloc] initWithFrame:cell.frame];
            myBackView.backgroundColor = [UIColor colorWithWhite:244/255.f alpha:1.0];
            [cell setSelectedBackgroundView:myBackView];
            
            cell.textLabel.highlightedTextColor = [UIColor colorWithRed:52/255.f green:56/255.f blue:60/255.f alpha:1.0];
            cell.textLabel.textColor = [UIColor whiteColor];
            cell.textLabel.font = [UIFont fontWithName:boldFontName size:14];
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height, cell.frame.size.width, 1)];
            line.backgroundColor = [UIColor colorWithRed:101/255.f green:104/255.f blue:111/255.f alpha:0.5];
            [cell.contentView addSubview:line];
        }
        
        if ([indexPath row] == enumMenuTypeRoom) {
            [cell.textLabel setText:@"Phòng"];
            cell.imageView.image = IMG_ICO_ROOM;
        }
        else if ([indexPath row] == enumMenuTypeHouse) {
            [cell.textLabel setText:@"Nhà"];
            cell.imageView.image = IMG_ICO_HOME;
            
        }
        else if ([indexPath row] == enumMenuTypeContact) {
            [cell.textLabel setText:@"Liên Hệ"];
            cell.imageView.image = IMG_ICO_CONTACT;
        }
    }
    else {
        cell = [tableView dequeueReusableCellWithIdentifier:identifierCellCenter];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierCellCenter];
            cell.backgroundColor = [UIColor clearColor];
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(cell.contentView.frame.size.width - WIDTH_TABLE_CELL + 3, 3, WIDTH_TABLE_CELL - 6, HEIGHT_TABLE_CELL - 8)];
            imageView.tag = _TAG_CELL_IMAGE;
            imageView.layer.borderColor = [UIColor whiteColor].CGColor;
            imageView.layer.borderWidth = 3.0f;
            imageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
            [cell.contentView addSubview:imageView];
            
            UIImageView *imageViewAvailability = [[UIImageView alloc] initWithFrame:CGRectMake(cell.contentView.frame.size.width - WIDTH_TABLE_CELL/2, 0, WIDTH_TABLE_CELL/2, HEIGHT_TABLE_CELL/2)];
            imageViewAvailability.tag = _TAG_CELL_AVAILABILITY_IMAGE_VIEW;
            imageViewAvailability.image = IMG_AVAILABILITY;
            imageViewAvailability.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
            [cell.contentView addSubview:imageViewAvailability];
            
            UIButton *btnRemainingDay = [[UIButton alloc] initWithFrame:CGRectMake(cell.contentView.frame.size.width - WIDTH_TABLE_CELL/2 - 3, -5, HEIGHT_TABLE_CELL/2, HEIGHT_TABLE_CELL/2 - 10)];
            btnRemainingDay.tag = _TAG_CELL_REMAINING_DAY_BUTTON;
            btnRemainingDay.titleLabel.font = [UIFont boldSystemFontOfSize:5];
            [btnRemainingDay setBackgroundImage:IMG_REMAINING_DAY forState:UIControlStateNormal];
            btnRemainingDay.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
            [cell.contentView addSubview:btnRemainingDay];
            
//            UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
//                                                initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
//            spinner.center = CGPointMake(imageView.frame.size.width / 2, imageView.frame.size.height / 2);
//            spinner.tag = _TAG_CELL_SPINNER;
//            spinner.autoresizingMask = UIViewAutoresizingFlexibleTopMargin
//            | UIViewAutoresizingFlexibleRightMargin
//            | UIViewAutoresizingFlexibleBottomMargin
//            | UIViewAutoresizingFlexibleLeftMargin;
//            spinner.color = UIColor.lightGrayColor;
//            [imageView addSubview:spinner];
            
            UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, cell.contentView.frame.size.width - 220, 30)];
            lblTitle.tag = _TAG_CELL_LTITLE;
            lblTitle.textColor = [UIColor colorWithRed:52/255.f green:56/255.f blue:60/255.f alpha:1.0];
            lblTitle.font = [UIFont fontWithName:boldFontName size:14];
            lblTitle.textAlignment = NSTextAlignmentLeft;
            lblTitle.backgroundColor = [UIColor clearColor];
            lblTitle.autoresizingMask = UIViewAutoresizingFlexibleWidth;
            [cell.contentView addSubview:lblTitle];
            
            lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(cell.contentView.frame.size.width - 200, 0, 110, 30)];
            lblTitle.textColor = [UIColor colorWithRed:215/255.f green:99/255.f blue:78/255.f alpha:1.0];
            lblTitle.tag = _TAG_CELL_RTITLE;
            lblTitle.font = [UIFont fontWithName:boldFontName size:14];
            lblTitle.textAlignment = NSTextAlignmentRight;
            lblTitle.backgroundColor = [UIColor clearColor];
            lblTitle.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
            [cell.contentView addSubview:lblTitle];
            
            lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, cell.contentView.frame.size.width - 90, 50)];
            lblTitle.textColor = [UIColor colorWithRed:52/255.f green:56/255.f blue:60/255.f alpha:1.0];
            lblTitle.tag = _TAG_CELL_CONTENT;
            lblTitle.backgroundColor = [UIColor clearColor];
            lblTitle.font = [UIFont fontWithName:fontName size:12];
            lblTitle.adjustsFontSizeToFitWidth =  YES;
            lblTitle.numberOfLines = 3;
            lblTitle.autoresizingMask = UIViewAutoresizingFlexibleWidth;
            [cell.contentView addSubview:lblTitle];
        }
        
        PersonNodeData *roomNode = nil;
        if (indexPath.row < _arrayMain.count) {
            roomNode = [_arrayMain objectAtIndex:indexPath.row];
        }
        
            // AVATAR
        UIImageView *imageView = (UIImageView *) [cell.contentView viewWithTag:_TAG_CELL_IMAGE];
        [imageView setImageWithURL:[NSURL URLWithString:roomNode.personSmallAvatarURL] placeholderImage:IMG_AVARTAR_DUMMY];
        
            // NAME
        UILabel *lblTitle = (UILabel*) [cell.contentView viewWithTag:_TAG_CELL_LTITLE];
        lblTitle.text = roomNode.personName;
        
            // STATUS
        UIImageView *imageViewAvailability = (UIImageView *) [cell.contentView viewWithTag:_TAG_CELL_AVAILABILITY_IMAGE_VIEW];
        UIButton *btnRemainingDay = (UIButton *) [cell.contentView viewWithTag:_TAG_CELL_REMAINING_DAY_BUTTON];
        if (roomNode.personPhongDepStatus.intValue > 0) {
            imageViewAvailability.hidden = YES;
            btnRemainingDay.hidden = NO;
            [btnRemainingDay setTitle:STRING_REMAINING_DAY_FORMAT(roomNode.personPhongDepStatus.intValue) forState:UIControlStateNormal];
        }
        else {
            imageViewAvailability.hidden = NO;
            btnRemainingDay.hidden = YES;
        }
        
            // PRICE
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        numberFormatter.groupingSeparator = @".";
        numberFormatter.decimalSeparator = @",";
        [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
        lblTitle = (UILabel*) [cell.contentView viewWithTag:_TAG_CELL_RTITLE];
        lblTitle.text = [NSString stringWithFormat:@"%@",
                          [numberFormatter stringFromNumber:[NSNumber numberWithFloat:roomNode.personPhongDepPrice.floatValue]]];
        if (roomNode.personPhongDepPrice.floatValue > 0) {
            lblTitle.hidden = NO;
        }
        else {
            lblTitle.hidden = YES;
        }
        
            // ADDRESS
        lblTitle = (UILabel*) [cell.contentView viewWithTag:_TAG_CELL_CONTENT];
        NSString *address = roomNode.personPhongDepAddress;
        NSString *district = roomNode.personPhongDepDistrict;
        NSString *city = roomNode.personPhongDepCity;
        lblTitle.text = STRING_ADDRESS_FORMAT(address, district, city);
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _centerTableView) {
        // MinhPB 2013/08/18
//        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        if (_paperFoldView.state != PaperFoldStateRightUnfolded)
            [_paperFoldView setPaperFoldState:PaperFoldStateRightUnfolded];
        
        if (indexPath.row < _arrayMain.count) {
            // DESELECT
            if (_pickedNode) {
                [_rightMapView deselectAnnotation:_pickedNode animated:YES];
            }
            _pickedNode = [_arrayMain objectAtIndex:indexPath.row];
            
            // GOTO LOCATION
            [self gotoLocationWithAnnotation:_pickedNode];
        }
    }
    else if (tableView == _leftTableView) {
        if (indexPath.row == enumMenuTypeContact) {
            [[AppViewController Shared] changeBackFromMainPageViewController];
        }
        else {
            // RESET
            _offsetHouse = 0;
            _offsetRoom = 0;
            _isRequestingTheNext = YES;
            [_paperFoldView setPaperFoldState:PaperFoldStateDefault];
            
            // LOAD INTERFACE
            [self loadInterface];
            
            // REQUEST
            [self requestTheNext];
        }
    }
}

#pragma mark - PaperFoldViewDelegate

- (void)paperFoldView:(id)paperFoldView didFoldAutomatically:(BOOL)automated toState:(PaperFoldState)paperFoldState
{
//    NSLog(@"did transition to state %i automated %i", paperFoldState, automated);
//   
//    NSLog(@"_leftTableView.indexPathForSelectedRow.row: %i", _leftTableView.indexPathForSelectedRow.row);
}


#pragma mark - APIRequesterProtocol

- (void)requestTheNext {
    if ([PersonDataManager roomsShared].categoryArray.count == 0 || [PersonDataManager housesShared].categoryArray.count == 0 || !_isRequestingTheNext) {
        [[AppViewController Shared] isRequesting:YES andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:_centerTableView.frame];
    }
    
    if (_isRequesting) {
        return;
    }
    
    _isRequesting = YES;
    
    NSString *requestURL = @"";
    if (_leftTableView.indexPathForSelectedRow.row == enumMenuTypeRoom) {
//        http://phongdep.vn/ws/free_rooms?secret_key=3eac3f982fd8d14919e92df28efcf0481b294a3efe4e7a987a1ab74ce1d1df80aacf02b57ea1f51057ffae73b9b60b9811eb990459b6c2b7777c0432306fb291&offset=1&limit=1
        requestURL = STRING_REQUEST_URL_PHONGDEP_GET_ROOMS(_offsetRoom, _limitRoom);
        [_APIRequester requestWithType:ENUM_API_REQUEST_TYPE_PHONGDEP_GET_ROOMS andRootURL:requestURL andPostMethodKind:YES andParams:nil andDelegate:self];
    }
    else if (_leftTableView.indexPathForSelectedRow.row == enumMenuTypeHouse) {
//        http://phongdep.vn/ws/house_list?secret_key=3eac3f982fd8d14919e92df28efcf0481b294a3efe4e7a987a1ab74ce1d1df80aacf02b57ea1f51057ffae73b9b60b9811eb990459b6c2b7777c0432306fb291&offset=1&limit=1
        requestURL = STRING_REQUEST_URL_PHONGDEP_GET_HOUSES(_offsetHouse, _limitHouse);
        [_APIRequester requestWithType:ENUM_API_REQUEST_TYPE_PHONGDEP_GET_HOUSES andRootURL:requestURL andPostMethodKind:YES andParams:nil andDelegate:self];
    }
    
#ifdef __DEBUG__
    NSLog(@"requestTheNext: %@", requestURL);
#endif
}

- (void)requestFinished:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type {
    _isRequesting = NO;
    
//#ifdef __DEBUG__
//    NSLog(@"requestFinished %@, request.responseStatusCode: %i", request.responseString, request.responseStatusCode);
//#endif
    
    [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
    
    NSError *error;
    SBJSON *sbJSON = [SBJSON new];
    
    if (![sbJSON objectWithString:[request responseString] error:&error] || request.responseStatusCode != 200 || !request) {
//        if (![ASIHTTPRequest isNetworkReachable]) {
//            ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_SERVER_ERROR);
//        }
#ifdef __DEBUG__
#else
        if (type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_TOKEN && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_UDID && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_USER_INFO) {
            ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_SERVER_ERROR);
        }
#endif
        return;
    }
    
    NSMutableDictionary *jsonData = [[sbJSON objectWithString:[request responseString] error:&error] objectForKey:STRING_RESPONSE_KEY_DATA];
    
    if (!jsonData || jsonData.count == 0) {
        return;
    }
    
    if (type == ENUM_API_REQUEST_TYPE_PHONGDEP_GET_ROOMS) {
        if (_offsetRoom == 0 && _isRequestingTheNext) {
            // CENTER TABLE VIEW
            [[PersonDataManager roomsShared] resetAllData];
        }
        
        // RIGHT MAP VIEW
        NSMutableArray *annotationsToRemove = [[NSMutableArray alloc] initWithArray:_rightMapView.annotations];
        [annotationsToRemove removeObject:_rightMapView.userLocation];
        [_rightMapView removeAnnotations:annotationsToRemove];
        
        int addedItems_Index = 0;
        for (NSString *key in jsonData.allKeys) {
            // CENTER TABLE VIEW
            NSMutableDictionary *dicJson = [jsonData objectForKey:key];
            PersonNodeData *roomNode = [[PersonNodeData alloc] initWithPersonName:key andPersonID:[dicJson objectForKey:STRING_RESPONSE_KEY_ROOM_ID] andPersonSmallAvatar:nil];
            roomNode.personPhongDepStatus = [dicJson objectForKey:STRING_RESPONSE_KEY_STATUS];
            roomNode.personSmallAvatarURL = [dicJson objectForKey:STRING_RESPONSE_KEY_IMAGE];
            roomNode.personPhongDepArea = [dicJson objectForKey:STRING_RESPONSE_KEY_AREA];
            roomNode.personPhongDepPrice = [dicJson objectForKey:STRING_RESPONSE_KEY_PRICE];
            roomNode.personPhongDepAddress = [dicJson objectForKey:STRING_RESPONSE_KEY_ADDRESS];
            roomNode.personPhongDepDistrict = [dicJson objectForKey:STRING_RESPONSE_KEY_DISTRICT];
            roomNode.personPhongDepCity = [dicJson objectForKey:STRING_RESPONSE_KEY_CITY];
            if ([[dicJson objectForKey:STRING_RESPONSE_KEY_LOCATION] objectForKey:STRING_RESPONSE_KEY_LATITUDE] != [NSNull null] &&
                [[dicJson objectForKey:STRING_RESPONSE_KEY_LOCATION] objectForKey:STRING_RESPONSE_KEY_LONGITUDE] != [NSNull null]) roomNode.coordinate = CLLocationCoordinate2DMake([[[dicJson objectForKey:STRING_RESPONSE_KEY_LOCATION] objectForKey:STRING_RESPONSE_KEY_LATITUDE] floatValue],
                                                                                                                                                                                    [[[dicJson objectForKey:STRING_RESPONSE_KEY_LOCATION] objectForKey:STRING_RESPONSE_KEY_LONGITUDE] floatValue]);
        
            // RIGHT MAP VIEW
            [_rightMapView addAnnotation:roomNode];
            
            // CHECK TO ADD: PREVIOUS ITEMS OR NEXT ITEMS
            if ([[PersonDataManager roomsShared] addNode:roomNode] == eIsDataAddSuccess) {
                addedItems_Index++;
            }
        }
        
        if (_isRequestingTheNext) {
            _offsetRoom += addedItems_Index;
        }
        else {
            _offsetRoom += _arrayMain.count;
        }
        [self loadInterface];
    }
    else if (type == ENUM_API_REQUEST_TYPE_PHONGDEP_GET_HOUSES) {
        if (_offsetRoom == 0 && _isRequestingTheNext) {
            [[PersonDataManager housesShared] resetAllData];
        }
        
        // RIGHT MAP VIEW
        NSMutableArray *annotationsToRemove = [[NSMutableArray alloc] initWithArray:_rightMapView.annotations];
        [annotationsToRemove removeObject:_rightMapView.userLocation];
        [_rightMapView removeAnnotations:annotationsToRemove];
        
        int addedItems_Index = 0;
        for (NSString *key in jsonData.allKeys) {
            // CENTER TABLE VIEW
            NSMutableDictionary *dicJson = [jsonData objectForKey:key];
            PersonNodeData *roomNode = [[PersonNodeData alloc] initWithPersonName:key andPersonID:[dicJson objectForKey:STRING_RESPONSE_KEY_HOUSE_ID] andPersonSmallAvatar:nil];
            roomNode.personPhongDepStatus = [dicJson objectForKey:STRING_RESPONSE_KEY_STATUS];
            roomNode.personSmallAvatarURL = [dicJson objectForKey:STRING_RESPONSE_KEY_IMAGE];
            roomNode.personPhongDepArea = [dicJson objectForKey:STRING_RESPONSE_KEY_AREA];
            roomNode.personPhongDepPrice = [dicJson objectForKey:STRING_RESPONSE_KEY_PRICE];
            roomNode.personPhongDepAddress = [dicJson objectForKey:STRING_RESPONSE_KEY_ADDRESS];
            roomNode.personPhongDepDistrict = [dicJson objectForKey:STRING_RESPONSE_KEY_DISTRICT];
            roomNode.personPhongDepCity = [dicJson objectForKey:STRING_RESPONSE_KEY_CITY];
            if ([[dicJson objectForKey:STRING_RESPONSE_KEY_LOCATION] objectForKey:STRING_RESPONSE_KEY_LATITUDE] != [NSNull null] &&
                [[dicJson objectForKey:STRING_RESPONSE_KEY_LOCATION] objectForKey:STRING_RESPONSE_KEY_LONGITUDE] != [NSNull null]) roomNode.coordinate = CLLocationCoordinate2DMake([[[dicJson objectForKey:STRING_RESPONSE_KEY_LOCATION] objectForKey:STRING_RESPONSE_KEY_LATITUDE] floatValue],
                                                             [[[dicJson objectForKey:STRING_RESPONSE_KEY_LOCATION] objectForKey:STRING_RESPONSE_KEY_LONGITUDE] floatValue]);
            
            // RIGHT MAP VIEW
            [_rightMapView addAnnotation:roomNode];
            
            // CHECK TO ADD: PREVIOUS ITEMS OR NEXT ITEMS
            if ([[PersonDataManager housesShared] addNode:roomNode] == eIsDataAddSuccess) {
                addedItems_Index++;
            }
        }
        
        if (_isRequestingTheNext) {
            _offsetHouse += addedItems_Index;
        }
        else {
            _offsetHouse += _arrayMain.count;
        }
        [self loadInterface];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request andType:(ENUM_API_REQUEST_TYPE)type {
    _isRequesting = NO;
    
//#ifdef __DEBUG__
//    NSLog(@"requestFailed %@, request.responseStatusCode: %i", request.responseString, request.responseStatusCode);
//#endif
    
    [[AppViewController Shared] isRequesting:NO andRequestType:ENUM_API_REQUEST_TYPE_INVALID andFrame:CGRectZero];
    
    if (![ASIHTTPRequest isNetworkReachable] && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_TOKEN && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_DEVICE_UDID && type != ENUM_API_REQUEST_TYPE_USER_UPDATE_USER_INFO) {
        ALERT(STRING_ALERT_CONNECTION_ERROR_TITLE, STRING_ALERT_CONNECTION_ERROR);
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

}

#pragma mark - MKMapViewDelegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    
    static NSString *AnnotationViewID = @"AnnotationViewID";
    
    LocationAnnotationView *annotationView =
    (LocationAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (annotationView == nil)
    {
        annotationView = [[LocationAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID andDelegate:self];
    }
    
    [annotationView loadInterfaceFromAnotation:annotation];
    
    return annotationView;
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
//    NSLog(@"calloutAccessoryControlTapped");
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
//    NSLog(@"didSelectAnnotationView");
    if ([view.annotation isKindOfClass:[MKUserLocation class]]) {
        return;
    }
    
    LocationAnnotationView *annotationView = (LocationAnnotationView *)view;
    [annotationView didSelectAnnotationView];
}

- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view {
//    NSLog(@"didDeselectAnnotationView");
    if ([view.annotation isKindOfClass:[MKUserLocation class]]) {
        return;
    }
    
    LocationAnnotationView *annotationView = (LocationAnnotationView *)view;
    [annotationView didDeselectAnnotationView];
}

#pragma mark - LocationAnnotationViewProtocol

- (void)touchesOneClickCallbackWithAnnotation:(id<MKAnnotation>)annotation
{
    if (_pickedNode) {
        [_rightMapView deselectAnnotation:_pickedNode animated:YES];
    }
    PersonNodeData *roomNode = (PersonNodeData *)annotation;
    _pickedNode = roomNode;
    [_rightMapView selectAnnotation:_pickedNode animated:YES];
    
    [_centerTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:[_arrayMain indexOfObject:roomNode] inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    
    // GOTO LOCATION
    MKCoordinateRegion newRegion;
    newRegion.center.latitude = roomNode.coordinate.latitude;
    newRegion.center.longitude = roomNode.coordinate.longitude;
    newRegion.span.latitudeDelta = _rightMapView.region.span.latitudeDelta;
    newRegion.span.longitudeDelta = _rightMapView.region.span.longitudeDelta;
    [_rightMapView setRegion:newRegion animated:YES];
    
    if ([roomNode isKindOfClass:[MKUserLocation class]]) {
        return;
    }
    else {
        _pickedNode = roomNode;
        [self showDetailPage];
//        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(showDetailPage) object:nil];
//        [self performSelector:@selector(showDetailPage) withObject:nil afterDelay:TIMER_CHANGING_VIEW];
    }
}

- (void)touchesDoubleClickCallbackWithAnnotation:(id<MKAnnotation>)annotation {
    
}

#pragma mark - UICGDirections Methods

- (void)updateRoute
{
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
	UICGDirectionsOptions *options = [[UICGDirectionsOptions alloc] init];
	options.travelMode = _rightDirections_TravelMode;
	City *mFirstCity = [[City alloc]init];
	mFirstCity.mCityName = _rightDirections_StartPoint;
	[_rightDirections_Main loadWithStartPoint:mFirstCity.mCityName endPoint:_rightDirections_Array options:options];
}

-(void)loadRouteAnnotations
{

}

-(void)removeRouteAnnotations
{

}


#pragma mark - UICGDirectionsDelegate

- (void)directionsDidFinishInitialize:(UICGDirections *)directions {
	[self updateRoute];
}

- (void)directions:(UICGDirections *)directions didFailInitializeWithError:(NSError *)error {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Map Directions" message:[error localizedFailureReason] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
	[alertView show];
}

- (void)directionsDidUpdateDirections:(UICGDirections *)indirections {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	
	UICGPolyline *polyline = [indirections polyline];
	NSArray *routePoints = [polyline routePoints];
	
	[_rightDirections_MapView loadRoutes:routePoints]; // Loads route by getting the array of all coordinates in the route.
    
	//Add annotations of different colors based on initial and final places.
	SBRouteAnnotation *startAnnotation = [[SBRouteAnnotation alloc] initWithCoordinate:[[routePoints objectAtIndex:0] coordinate]
                                                                                 title:_rightDirections_StartPoint
                                                                        annotationType:SBRouteAnnotationTypeStart];
	SBRouteAnnotation *endAnnotation = [[SBRouteAnnotation alloc] initWithCoordinate:[[routePoints lastObject] coordinate]
                                                                               title:_rightDirections_EndPoint
                                                                      annotationType:SBRouteAnnotationTypeEnd];
	
	[_rightDirections_MapView.mapView addAnnotations:[NSArray arrayWithObjects:startAnnotation, endAnnotation,nil]];
}

- (void)directions:(UICGDirections *)directions didFailWithMessage:(NSString *)message {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Map Directions" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
	[alertView show];
}

#pragma mark - DIRECTIONS

- (void)gotoCurrentLocation {
    [self gotoLocationWithAnnotation:_rightMapView.userLocation];
}

- (void)gotoLocationWithAnnotation:(id<MKAnnotation>)annotation {
    PersonNodeData *roomNode = (PersonNodeData *)annotation;
    
    // INTERFACE
    CATransition *animation = [CATransition animation];
    [animation setDuration:TIMER_CHANGING_VIEW];
    [animation setType:kCATransitionFade];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    
    _rightDirections_MapView.hidden = YES;
    [_rightDirections_MapView.layer addAnimation:animation forKey:@"animation"];
    
    if ([roomNode isKindOfClass:[MKUserLocation class]]) {
        _btnMap_GetDirections.hidden = YES;
    }
    else {
        _btnMap_GetDirections.hidden = NO;
    }
    
    // GOTO LOCATION
    MKCoordinateRegion newRegion;
    newRegion.center.latitude = roomNode.coordinate.latitude;
    newRegion.center.longitude = roomNode.coordinate.longitude;
    newRegion.span.latitudeDelta = _rightMapView.region.span.latitudeDelta;
    newRegion.span.longitudeDelta = _rightMapView.region.span.longitudeDelta;
    [_rightMapView setRegion:newRegion animated:YES];
    
    // SELECT
    [_rightMapView selectAnnotation:roomNode animated:YES];
}

- (void)getDirectionsFromCurrentLocation {
    if (!_pickedNode) {
        return;
    }
    
    // INTERFACE
    CATransition *animation = [CATransition animation];
    [animation setDuration:TIMER_CHANGING_VIEW];
    [animation setType:kCATransitionFade];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    
    _rightDirections_MapView.hidden = NO;
    [_rightDirections_MapView.layer addAnimation:animation forKey:@"animation"];
    
    MKCoordinateRegion newRegion;
    newRegion.center.latitude = _rightMapView.userLocation.coordinate.latitude;
    newRegion.center.longitude = _rightMapView.userLocation.coordinate.longitude;
    newRegion.span.latitudeDelta = _rightMapView.region.span.latitudeDelta;
    newRegion.span.longitudeDelta = _rightMapView.region.span.longitudeDelta;
    [_rightDirections_MapView.mapView setRegion:newRegion animated:YES];
    
    // DIRECTIONS
    _rightDirections_Main = [UICGDirections sharedDirections];
    _rightDirections_Main.delegate = self;
    
    _rightDirections_StartPoint = [NSString stringWithFormat:@"%f,%f",_rightMapView.userLocation.coordinate.latitude,_rightMapView.userLocation.coordinate.longitude];
//    _rightDirections_StartPoint = @"Current Location";
    
    _rightDirections_EndPoint = [NSString stringWithFormat:@"%f,%f",_pickedNode.coordinate.latitude,_pickedNode.coordinate.longitude];
//    _rightDirections_EndPoint = _pickedNode.personName;
    
    NSMutableArray *destinationArray = [[NSMutableArray alloc] init];
    [destinationArray addObject:_rightDirections_EndPoint];
    
    // RELOAD INTERFACE
    [_rightDirections_Main reloadInterface];
    [_rightDirections_MapView reloadInterface];
    
    // SET NEW
    _rightDirections_Array = destinationArray;
    _rightDirections_TravelMode = UICGTravelModeDriving;
    
//    if (_rightDirections_Main.isInitialized) {
//        [self updateRoute];
//    }
    [self updateRoute];
}

#pragma mark - DETAIL PAGE

- (void)showDetailPage {
    [self showDetailPageWithAnnotation:_pickedNode];
}

- (void)showDetailPageWithAnnotation:(id<MKAnnotation>)annotation {
    PersonNodeData *roomNode = (PersonNodeData *)annotation;
    
    if (_leftTableView.indexPathForSelectedRow.row == enumMenuTypeRoom) {
        RoomDetailView *roomDetailView = [[RoomDetailView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
                                                                         title:roomNode.personName
                                                                        roomID:roomNode.personID];
        roomDetailView.parentController = self;
        [self.view addSubview:roomDetailView];
        // Show the panel from the center of the button that was pressed
        [roomDetailView showFromPoint:[self.view center]];
    }
    else if (_leftTableView.indexPathForSelectedRow.row == enumMenuTypeHouse) {
        HouseDetailView *houseDetailView = [[HouseDetailView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
                                                                            title:roomNode.personName
                                                                            houseID:roomNode.personID];
        houseDetailView.parentController = self;
        [self.view addSubview:houseDetailView];
        // Show the panel from the center of the button that was pressed
        [houseDetailView showFromPoint:[self.view center]];
    }
}

@end
